// -----------------------------------------------------------------------
//  <copyright file="RandomSlaveDatabaseSelector.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-11-08 21:57</last-date>
// -----------------------------------------------------------------------

using DaprPlus.EntityFrameworkCore.Properties;

using OSharp.Extensions;


namespace DaprPlus.EntityFrameworkCore;

/// <summary>
/// 随机从数据库选择器
/// </summary>
public class RandomSlaveDatabaseSelector : ISlaveDatabaseSelector
{
    private static readonly Random _random = new();
    private readonly ILogger _logger;

    /// <summary>
    /// 初始化一个<see cref="RandomSlaveDatabaseSelector"/>类型的新实例
    /// </summary>
    public RandomSlaveDatabaseSelector(IServiceProvider provider)
    {
        _logger = provider.GetLogger(GetType());
    }

    /// <summary>
    /// 获取 名称
    /// </summary>
    public string Name => "Random";

    /// <summary>
    /// 从所有从数据库中选择一个
    /// </summary>
    public SlaveDatabaseOptions Select(SlaveDatabaseOptions[] slaves)
    {
        Check.NotNullOrEmpty(slaves, nameof(slaves));
        
        var slave = _random.NextItem(slaves);
        _logger.LogInformation(ResEFCore.Format_Entity_SelectSlave_Random, slave.Name);
        return slave;
    }
}
